package com.geeklei.player;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.geeklei.media.ui.IUserEventListener;
import com.geeklei.media.ui.GeekleiMediaUi;
import com.geeklei.media.ui.MediaPlayerListener;
import com.geeklei.media.ui.common.ErrorEvent;
import com.geeklei.media.ui.menu.popup.ItemWraper;
import com.geeklei.media.ui.menu.popup.ListPopupWindow;

import java.io.File;
import java.util.ArrayList;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by leixun on 16/7/11.
 */
public class PlayVideoActivity extends Activity implements IUserEventListener, MediaPlayerListener {
    private String TAG = com.geeklei.player.PlayVideoActivity.class.getSimpleName();
    String item = "http://vdata.ismartv.tv/qyrrs?url=http%3A%2F%2Ftu.video.qiyi.com%2Ftbox%2Fmplay3u8%2FODliYjg4OTMzYzk0N2Y5NTZlNjRlMDhlNDQ3Nzg5ZDMvZDFlNzZhMjk3MDI4NGVmMDgwZTJjYzk4ODhhYTFkYWQvMTE0MTI4%2F0_Mjg0Njk1.m3u8&amp;uuid=3612ccce17a94d8b9c418dc9c05361581&amp;quality=normal&amp;sn=4107ac006a357f41&amp;clipid=216798";
    String item2 = "http://vdata.ismartv.tv/qyrrs?url=http%3A%2F%2Ftu.video.qiyi.com%2Ftbox%2Fmplay3u8%2FODliYjg4OTMzYzk0N2Y5NTZlNjRlMDhlNDQ3Nzg5ZDMvZDFlNzZhMjk3MDI4NGVmMDgwZTJjYzk4ODhhYTFkYWQvMTE0MTI4%2F0_Mjg0Njk1.m3u8&amp;uuid=3612ccce17a94d8b9c418dc9c05361581&amp;quality=normal&amp;sn=4107ac006a357f41&amp;clipid=216798";
    GeekleiMediaUi geekleiMediaUi;

    ArrayList<CustomVideoBean> beans = new ArrayList<CustomVideoBean>();

    class CustomVideoBean {
        public String name;
        public String url;

        public CustomVideoBean(String name, String url) {
            this.name = name;
            this.url = url;
        }
    }

    int currentPlayPosition = 0;

    protected ArrayList<ItemWraper> mPlayList;
    private ItemWraper currentSpped;
    private String[] speeds;

    public static final String CACHE_PATH = Environment.getExternalStorageDirectory().getPath()
            + File.separator + "geeklei" + File.separator + "cache";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beans = new ArrayList<>();
        String[] medias = getResources().getStringArray(R.array.online_media);
        for (int i = 0; i < medias.length; i++) {
            beans.add(new CustomVideoBean("name" + i, medias[i]));
        }
        speeds = getResources().getStringArray(R.array.planets_array);
        geekleiMediaUi = new GeekleiMediaUi(this, this, this, false);
        setContentView(geekleiMediaUi.getContentView());
    }

    @Override
    protected void onStart() {
        super.onStart();
        CustomVideoBean bean = null;
        if (currentPlayPosition == -1) {
            bean = beans.get(0);
        } else {
            bean = beans.get(currentPlayPosition);
        }
        geekleiMediaUi.play(Uri.parse(bean.url), bean.name);
        geekleiMediaUi.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        geekleiMediaUi.onDestroy();
    }

    @Override
    public void playNext() {
        ++currentPlayPosition;
        if (currentPlayPosition >= beans.size()) {
            Toast.makeText(this, "当前已播放到最后一个视频", Toast.LENGTH_SHORT).show();
            currentPlayPosition--;
            return;
        }
        play();
    }

    @Override
    public ArrayList<ItemWraper> getPlayList() {
        if (mPlayList == null) {
            mPlayList = new ArrayList<ItemWraper>();
            int size = beans.size();
            for (int i = 0; i < size; i++) {
                ItemWraper itemWraper = new ItemWraper(beans.get(i).name, beans.get(i).hashCode());
                mPlayList.add(itemWraper);
            }
        }
        return mPlayList;
    }

    @Override
    public ListPopupWindow.OnSourceSelectListener getPlaySelectListener() {
        return onSourceSelectListener;
    }

    @Override
    public ItemWraper getCurrentPlay() {
        if (currentPlayPosition > beans.size()) {
            return null;
        } else {
            return new ItemWraper(beans.get(currentPlayPosition).name, beans.get(currentPlayPosition).hashCode());
        }
    }

    @Override
    public ArrayList<ItemWraper> getSpeedList() {
        ArrayList<ItemWraper> list = new ArrayList<ItemWraper>();
        int size = speeds.length;
        for (int i = 0; i < size; i++) {
            ItemWraper item = new ItemWraper(speeds[i], speeds[i].hashCode());
            list.add(item);
        }
        return list;
    }

    @Override
    public ListPopupWindow.OnSourceSelectListener getSpeedSelectListener() {
        return onSpeedSelectListener;
    }

    @Override
    public ItemWraper getCurrentSpeed() {
        if (currentSpped == null) {
            if (speeds.length > 4) {
                currentSpped = new ItemWraper(speeds[3], speeds[3].hashCode());
            }
        }
        return currentSpped;
    }

    @Override
    public void mBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {

    }

    @Override
    public void mCompletion(IMediaPlayer iMediaPlayer) {
        iMediaPlayer.pause();
    }

    @Override
    public ErrorEvent mError(IMediaPlayer iMediaPlayer, int what, int extra) {
        StringBuffer stringBuffer = new StringBuffer();
        Log.d("error----------------", what + "    " + extra);
        //如果没网络情况,不上传记录,直接返回
        stringBuffer.append("<br>错误信息:" + "what=" + what + "  extra=" + extra);


        //突然断网时的ui同步更新

//        if (extra == -112) {
//            return new ErrorEvent(stringBuffer.toString(), reLoginClickListener);
//        } else if (extra == -138) {
//            return new ErrorEvent(stringBuffer.toString(), refreshClickListener);
//        } else if (extra == -139) {
//            return new ErrorEvent(stringBuffer.toString(), null);
//        }
        return new ErrorEvent(stringBuffer.toString(), null);
    }

    @Override
    public void mPrepared(IMediaPlayer iMediaPlayer) {
//        iMediaPlayer.setCacheDir(CACHE_PATH);
//        iMediaPlayer.seekTo(mLastPos);
        iMediaPlayer.start();
    }

    @Override
    public void mInfo(IMediaPlayer iMediaPlayer, int what, int extra) {
//        一般视频统计使用
//        switch (what) {
//            case KooMediaPlayer.MEDIA_INFO_BUFFERING_START:
//                bufferTime = System.currentTimeMillis();
//                startBufferTime = bufferTime;
//                break;
//            case KooMediaPlayer.MEDIA_INFO_BUFFERING_END:
//                bufferTime = System.currentTimeMillis() - bufferTime;
//                endBufferTime = System.currentTimeMillis();
//                setVideoBufferInfo();
//                break;
//            case KooMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
//                if (bufferSpeeds != null && bufferSpeeds.size() < 4) {
//                    bufferSpeeds.add(extra);
//                }
//                break;
//        }
    }

    protected void setSpeed() {
        if (currentSpped == null) {
            getCurrentSpeed();
        }
        if (currentSpped != null) {
            CharSequence speedStr = currentSpped.getSource().subSequence(0, currentSpped.getSource().length() - 1);
            float spped = Float.valueOf((String) speedStr);
            geekleiMediaUi.setSpeed(spped);
        }
    }

    private ListPopupWindow.OnSourceSelectListener onSourceSelectListener = new ListPopupWindow.OnSourceSelectListener() {
        @Override
        public void onSourceSelect(int i, ItemWraper itemWraper) {
            currentPlayPosition = i;
            if (i >= beans.size()) {
                Log.d("llll", "播放列表已经越界");
                return;
            } else {
                currentPlayPosition = i;
                play();
            }
        }
    };

    private ListPopupWindow.OnSourceSelectListener onSpeedSelectListener = new ListPopupWindow.OnSourceSelectListener() {
        @Override
        public void onSourceSelect(int i, ItemWraper itemWraper) {
            CharSequence speedStr = itemWraper.getSource().subSequence(0, itemWraper.getSource().length() - 1);
            float spped = Float.valueOf((String) speedStr);
            geekleiMediaUi.getMeidaPlayerController().setSpeed(spped); // spinner设置speed
            currentSpped = itemWraper;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //如果是back键,交给player监听
            return geekleiMediaUi.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    private View.OnClickListener reLoginClickListener = new View.OnClickListener() {
        public void onClick(View view) {
//            finish();
        }
    };

    private View.OnClickListener refreshClickListener = new View.OnClickListener() {
        public void onClick(View view) {
//            play();
        }
    };

    class BroadcastReceiverMgr extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            } else {
                doReceivePhone(context, intent);
            }
        }

        /**
         * 处理电话广播.
         *
         * @param context
         * @param intent
         */
        public void doReceivePhone(Context context, Intent intent) {
            String phoneNumber = intent.getStringExtra(
                    TelephonyManager.EXTRA_INCOMING_NUMBER);
            TelephonyManager telephony =
                    (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            int state = telephony.getCallState();
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.i(TAG, "[Broadcast]等待接电话=" + phoneNumber);
                    phonePause();
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.i(TAG, "[Broadcast]电话挂断=" + phoneNumber);
//                    mVideoFragment.phoneStart();
                    phoneStart();
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.i(TAG, "[Broadcast]通话中=" + phoneNumber);
                    break;
            }
        }
    }

    private void phonePause() {
        if (geekleiMediaUi.getMeidaPlayerController().isPlaying()) {
            geekleiMediaUi.getMeidaPlayerController().pause();
        }
    }

    private void phoneStart() {
        geekleiMediaUi.getMeidaPlayerController().start();
    }

    private void play() {
        CustomVideoBean bean = beans.get(currentPlayPosition);
        geekleiMediaUi.play(Uri.parse(bean.url), bean.name);
        setSpeed();
    }

    @Override
    public boolean canPlay() {
        return true;
    }
}
